package top.tangyh.lamp.care.controller;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.w3c.dom.*;
import top.tangyh.lamp.care.vo.result.FuerInpatientInfoResult;

import javax.xml.parsers.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: zqb
 * @date: 2024/10/28 14:45
 */
public class TestWebservice {


    public static void main(String[] args) {
        try {
            // WebService 地址
            URL url = new URL("http://172.16.4.240:18131/wondersHSBP/WSEntry?wsdl");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和属性
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
            connection.setDoOutput(true);

            // SOAP 请求的 XML
            String soapXML = """
                        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:won="www.WondersHSBP.com">
                            <soap:Header/>
                            <soap:Body>
                                <won:invokeRequest>
                                    <won:parameter>
                                        <![CDATA[
                                            <body><head><password></password><userid></userid><trans_no>SERV_HSB_SC0002</trans_no></head><request></request></body>
                                        ]]>
                                    </won:parameter>
                                </won:invokeRequest>
                            </soap:Body>
                        </soap:Envelope>
                    """;

            // 发送 SOAP 请求
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = soapXML.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }

            // 检查响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("请求成功!");
                // 读取和处理响应...
                // (可以使用 BufferedReader 去读取响应内容)
                // 读取响应内容
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }

                    // 输出响应内容
                    System.out.println("响应内容: " + response.toString());
                    String content = response.toString();

                }
            } else {
                System.out.println("请求失败，响应代码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getContent() {
        String content = "";
        try {
            // WebService 地址
            URL url = new URL("http://172.16.4.240:18131/wondersHSBP/WSEntry?wsdl");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和属性
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
            connection.setDoOutput(true);

            // SOAP 请求的 XML
            String soapXML = """
                    <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:won="www.WondersHSBP.com">
                        <soap:Header/>
                        <soap:Body>
                            <won:invokeRequest>
                                <won:parameter>
                                    <![CDATA[
                                        <body><head><password></password><userid></userid><trans_no>SERV_HSB_SC0002</trans_no></head><request></request></body>
                                    ]]>
                                </won:parameter>
                            </won:invokeRequest>
                        </soap:Body>
                    </soap:Envelope>
                """;

            // 发送 SOAP 请求
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] input = soapXML.getBytes(StandardCharsets.UTF_8);
                outputStream.write(input, 0, input.length);
            }

            // 检查响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("请求成功!");
                // 读取响应内容
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }

                    // 输出响应内容
                    System.out.println("响应内容: " + response.toString());
                    content = response.toString();
                }
            } else {
                System.out.println("请求失败，响应代码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return content;
    }

    public List<FuerInpatientInfoResult> analysisData() {
        String soapResponse = getContent();
        List<FuerInpatientInfoResult> fuerInpatientInfoResultList = new ArrayList<>();

        try {
            // 解析SOAP响应
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputStream inputStream = new ByteArrayInputStream(soapResponse.getBytes(StandardCharsets.UTF_8));
            Document document = builder.parse(inputStream);

            // 获取won:result节点
            NodeList resultList = document.getElementsByTagName("won:result");

            if (resultList.getLength() > 0) {
                // 从won:result节点中获取INPATIENTINFO节点
                String cdata = resultList.item(0).getTextContent();
                DocumentBuilderFactory innerFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder innerBuilder = innerFactory.newDocumentBuilder();
                InputStream innerInputStream = new ByteArrayInputStream(cdata.getBytes(StandardCharsets.UTF_8));
                Document innerDocument = innerBuilder.parse(innerInputStream);

                // 获取INPATIENTINFO节点
                NodeList inpatientInfoList = innerDocument.getElementsByTagName("INPATIENTINFO");

                System.out.println("患者patientCon：" + inpatientInfoList.getLength());
                // 遍历INPATIENTINFO节点
                for (int i = 0; i < inpatientInfoList.getLength(); i++) {
                    Element inpatientInfo = (Element) inpatientInfoList.item(i);
                    String deptCode = getChildNodeValue(inpatientInfo, "DEPTCODE");

                    // 仅输出DEPTCODE为132的节点
                    if ("132".equals(deptCode)) {
                        System.out.println("找到DEPTCODE为132的病人信息:");
                        System.out.println("PATIENTID: " + getChildNodeValue(inpatientInfo, "PATIENTID"));
                        System.out.println("PATIENTNAME: " + getChildNodeValue(inpatientInfo, "PATIENTNAME"));
                        System.out.println("INPATIENTID: " + getChildNodeValue(inpatientInfo, "INPATIENTID"));
                        System.out.println("AGE: " + getChildNodeValue(inpatientInfo, "AGE"));
                        System.out.println("MOBILE: " + getChildNodeValue(inpatientInfo, "MOBILE"));
                        System.out.println("=================================");

                        // 创建结果对象并添加到列表
                        FuerInpatientInfoResult fuerInpatientInfoResult=new FuerInpatientInfoResult();
                        // 设置属性
                        fuerInpatientInfoResult.setPatientId(getChildNodeValue(inpatientInfo, "PATIENTID"));
                        fuerInpatientInfoResult.setHosTime(getChildNodeValue(inpatientInfo, "HOSTIME"));
                        fuerInpatientInfoResult.setInpatientId(getChildNodeValue(inpatientInfo, "INPATIENTID"));
                        fuerInpatientInfoResult.setPatientName(getChildNodeValue(inpatientInfo, "PATIENTNAME"));
                        fuerInpatientInfoResult.setSexCode(getChildNodeValue(inpatientInfo, "SEXCODE"));
                        fuerInpatientInfoResult.setSex(getChildNodeValue(inpatientInfo, "SEX"));
                        fuerInpatientInfoResult.setDob(getChildNodeValue(inpatientInfo, "DOB"));
                        fuerInpatientInfoResult.setAge(Integer.parseInt(getChildNodeValue(inpatientInfo, "AGE")));
                        fuerInpatientInfoResult.setDocumentId(getChildNodeValue(inpatientInfo, "DOCUMENTID"));
                        fuerInpatientInfoResult.setBloodGroup(getChildNodeValue(inpatientInfo, "BLOODGROUP"));
                        fuerInpatientInfoResult.setAddress(getChildNodeValue(inpatientInfo, "ADDRESS"));
                        fuerInpatientInfoResult.setIdTypeCode(getChildNodeValue(inpatientInfo, "IDTYPECODE"));
                        fuerInpatientInfoResult.setIdType(getChildNodeValue(inpatientInfo, "IDTYPE"));
                        fuerInpatientInfoResult.setIdNo(getChildNodeValue(inpatientInfo, "IDNO"));
                        fuerInpatientInfoResult.setYbFlag(Integer.parseInt(getChildNodeValue(inpatientInfo, "YBFLAG")));
                        fuerInpatientInfoResult.setPatType(getChildNodeValue(inpatientInfo, "PATTYPE"));
                        fuerInpatientInfoResult.setPatTypeCode(getChildNodeValue(inpatientInfo, "PATTYPECODE"));
                        fuerInpatientInfoResult.setMobile(getChildNodeValue(inpatientInfo, "MOBILE"));
                        fuerInpatientInfoResult.setInsureCardNo(getChildNodeValue(inpatientInfo, "INSURECARDNO"));
                        fuerInpatientInfoResult.setAccInfo(getChildNodeValue(inpatientInfo, "ACCINFO"));
                        fuerInpatientInfoResult.setAccInfoBalance(getChildNodeValue(inpatientInfo, "ACCINFOBALANCE"));
                        fuerInpatientInfoResult.setAccInfoNo(getChildNodeValue(inpatientInfo, "ACCINFONO"));
                        fuerInpatientInfoResult.setPatientCard(getChildNodeValue(inpatientInfo, "PATIENTCARD"));
                        fuerInpatientInfoResult.setDeptCode(getChildNodeValue(inpatientInfo, "DEPTCODE"));
                        fuerInpatientInfoResult.setDeptName(getChildNodeValue(inpatientInfo, "DEPTNAME"));
                        fuerInpatientInfoResult.setWardCode(getChildNodeValue(inpatientInfo, "WARDCODE"));
                        fuerInpatientInfoResult.setWardName(getChildNodeValue(inpatientInfo, "WARDNAME"));
                        fuerInpatientInfoResult.setBedNo(getChildNodeValue(inpatientInfo, "BEDNO"));
                        fuerInpatientInfoResult.setInHosDate(getChildNodeValue(inpatientInfo, "INHOSDATE"));
                        fuerInpatientInfoResult.setOutHosStatus(getChildNodeValue(inpatientInfo, "OUTHOSSTATUS"));
                        fuerInpatientInfoResult.setOutHostTime(getChildNodeValue(inpatientInfo, "OUTHOSTIME"));
                        fuerInpatientInfoResult.setNursingLevel(Integer.parseInt(getChildNodeValue(inpatientInfo, "NURSINGLEVEL")));
                        fuerInpatientInfoResult.setDisease(Integer.parseInt(getChildNodeValue(inpatientInfo, "DISEASE")));

                        fuerInpatientInfoResultList.add(fuerInpatientInfoResult);
                    }
                }
            } else {
                System.out.println("未找到won:result节点");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return fuerInpatientInfoResultList;
    }



    private static String getChildNodeValue(Element parent, String nodeName) {
        NodeList nodeList = parent.getElementsByTagName(nodeName);
        if (nodeList.getLength() > 0) {
            return nodeList.item(0).getTextContent().trim();
        }
        return null;
    }

}
